
import classNames from "classnames"
import React,{useRef, useState,useEffect} from 'react'

import { useDispatch } from 'react-redux'
import "../styles/index.css"

import { todoDel, todoMode } from '../store/actions'
import { todoDone } from '../store/actions'

export default function TodoItem(props) {
    const dispatch = useDispatch()
    const { item}=props;

    const [currentId,setCurrentId]=useState('');
    const [currenAct,setCurrentAct]=useState('');

    const handleDel=(id)=>dispatch(todoDel(id))
    const handleDone=(id)=>dispatch(todoDone(id))
    const handleDbClick=(id)=>{
        setCurrentId(id);
      }
    const inputRef=useRef();
    const onhandleBlur=(id)=>{
        setCurrentId('');
        dispatch(todoMode(currenAct,id));
      }
    const handleEditChange=(e)=>{
      if(e.key==="Escape"){
        setCurrentAct("");
        setCurrentId('');
        return;
      }
      setCurrentAct(e.target.value)
    }
    
    useEffect(()=>{ //异步操作，刷新之后获取焦点，如不采取这种方案，那么获取焦点先于选中则不可编辑
        inputRef.current.focus();
        },[currentId])
  return (
    <li
    className={classNames({
      completed: item.done,
      editing: currentId === item.id,
    })}
  >
    <div className='view'>
      <input
        className='toggle'
        type='checkbox'
        checked={item.done}
        onChange={() => handleDone(item.id)}
      />
      <label onDoubleClick={() => handleDbClick(item.id)}>{item.act}</label>
      <button className='destroy' onClick={() => handleDel(item.id)}></button>
    </div>
    <input
      className='edit'
      value={currenAct}
      onChange={handleEditChange}
      ref={inputRef}
      onBlur={()=>onhandleBlur(item.id)}
      
    />
  </li>
  )
}
